package beautiful.butterfly.drds.data_exchange.core.statistics.container.communicator;


import beautiful.butterfly.drds.data_exchange.core.statistics.communication.Communication;
import beautiful.butterfly.drds.data_exchange.core.statistics.container.collector.AbstractCollector;
import beautiful.butterfly.drds.data_exchange.core.statistics.container.report.AbstractReporter;
import beautiful.butterfly.drds.data_exchange.core.util.container.Constants;
import beautiful.butterfly.drds.data_exchange.dataxservice.face.domain.enums.State;
import common.statistics.JvmInfo;
import common.util.Configuration;

import java.util.List;
import java.util.Map;

public abstract class AbstractContainerCommunicator
{
    private Configuration configuration;
    private AbstractCollector collector;
    private AbstractReporter reporter;

    private Long jobId;

    private JvmInfo jvmInfo = JvmInfo.getJvmInfo();
    private long lastReportTime = System.currentTimeMillis();


    public AbstractContainerCommunicator(Configuration configuration)
    {
        this.configuration = configuration;
        this.jobId = configuration.getLong(Constants.datax_core_container_job_id);
    }

    public Configuration getConfiguration()
    {
        return this.configuration;
    }

    public AbstractCollector getCollector()
    {
        return collector;
    }

    public void setCollector(AbstractCollector collector)
    {
        this.collector = collector;
    }

    public AbstractReporter getReporter()
    {
        return reporter;
    }

    public void setReporter(AbstractReporter reporter)
    {
        this.reporter = reporter;
    }

    public Long getJobId()
    {
        return jobId;
    }

    public abstract void registerCommunication(List<Configuration> configurationList);

    public abstract Communication collect();

    public abstract void report(Communication communication);

    public abstract State collectState();

    public abstract Communication getCommunication(Integer id);

    /**
     * 当 实现是 TGContainerCommunicator 时，返回的 Map: key=taskId, value=Communication
     * 当 实现是 JobContainerCommunicator 时，返回的 Map: key=taskGroupId, value=Communication
     */
    public abstract Map<Integer, Communication> getCommunicationMap();

    public void resetCommunication(Integer id)
    {
        Map<Integer, Communication> map = getCommunicationMap();
        map.put(id, new Communication());
    }

    public void reportVmInfo()
    {
        long now = System.currentTimeMillis();
        //每5分钟打印一次
        if (now - lastReportTime >= 300000)
        {
            //当前仅打印
            if (jvmInfo != null)
            {
                jvmInfo.updateJvmInfo(true);
            }
            lastReportTime = now;
        }
    }
}